import 'dart:io';

import 'package:cjybase/base/base_page.dart';
import 'package:cjybase/network/log_Interceptor.dart';
import 'package:cjybase/util/file_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class Net {
  static Dio dio = new Dio();

  /// 初始化网络请求数据
  /// baseUrl 服务器接口地址
  /// headers 请求头参数
  static init(String baseUrl, Map<String, dynamic> headers) {
    dio.options.baseUrl = baseUrl;
    dio.options.headers = headers;
    dio.interceptors.clear();
    dio.interceptors.add(DioLogInterceptor());
  }

  /// get请求
  /// intf 接口名称
  /// param 请求参数
  /// headers 请求头参数
  /// success 成功的回调
  /// error 失败的回调
  static get(String intf,
      {Map<String, dynamic> param,
      Map<String, dynamic> headers,
      Function success,
      Function error}) async {
    _request(intf, param, headers, "GET", success, error);
  }

  /// post请求
  /// intf 接口名称
  /// param 请求参数
  /// headers 请求头参数
  /// success 成功的回调
  /// error 失败的回调
  static post(String intf,
      {Map<String, dynamic> param,
      Map<String, dynamic> headers,
      Function success,
      Function error}) async {
    _request(intf, param, headers, "POST", success, error);
  }

  static _request(
      String intf,
      Map<String, dynamic> param,
      Map<String, dynamic> headers,
      String method,
      Function success,
      Function error) async {
    try {
      var respone = method == "GET"
          ? await dio.get(intf,
              queryParameters: param,
              options: Options(headers: headers, method: method))
          : await dio.post(intf,
              queryParameters: param,
              data: param,
              options: Options(headers: headers, method: method));
      success(respone.data);
    } catch (e) {
      error(e);
      if (e.response == null) {
        if (e.error.message.isEmpty || e.error.osError.errorCode == 101) {
          EasyLoading.showToast("网络异常，请检查网路");
          return;
        }
      } else {
        if (e.response.statusCode == 404) {
          EasyLoading.showToast("服务器连接异常");
          return;
        }
        if (e.response.statusCode == 500) {
          EasyLoading.showToast("服务器异常");
          return;
        }
        if (e.response.statusCode == 401 || e.response.statusCode == 400) {
          EasyLoading.showToast(e.response.data['msg'].toString());
          return;
        }
      }
    }
  }

  /// download 下载
  /// urlPath 下载地址
  /// savePath 保存地址
  /// param 请求参数
  /// headers 请求头参数
  /// progress 进度回调
  /// finish 完成回调
  /// error 失败回调
  static download(String urlPath, String savePath,
      {Map<String, dynamic> param,
      Map<String, dynamic> headers,
      Function progress,
      Function finish,
      Function error}) async {
    try {
      await dio.download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        progress((count / total * 100).toStringAsFixed(0) + "%");
        if (count == total) {
          finish(savePath);
        }
      }, queryParameters: param, options: Options(headers: headers));
    } catch (e) {
      error(e);
      if (e.response == null) {
        if (e.error.message.isEmpty || e.error.osError.errorCode == 101) {
          EasyLoading.showToast("网络异常，请检查网路");
          return;
        }
      } else {
        if (e.response.statusCode == 404) {
          EasyLoading.showToast("服务器连接异常");
          return;
        }
        if (e.response.statusCode == 500) {
          EasyLoading.showToast("服务器异常");
          return;
        }
        if (e.response.statusCode == 401 || e.response.statusCode == 400) {
          EasyLoading.showToast(e.response.data['msg'].toString());
          return;
        }
      }
    }
  }

  /// 文件上传
  static putFile(String intf, File file,
      {Map<String, dynamic> param, Function success, Function error}) async {
    try {
      FormData formdata = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          file.path, //图片路径
          filename: FileUtil.getFileName(file.path),
        ), //文件名称
      });
      // param["file"] = await MultipartFile.fromFile(
      //   file.path, //图片路径
      //   filename: Util.getFileName(file.path),
      // ); //图片
      var respone = await dio.post(
        intf,
        data: formdata,
        queryParameters: param,
      );
      success(respone.data);
    } catch (e) {
      error(e);
      if (e.response == null) {
        if (e.error.message.isEmpty || e.error.osError.errorCode == 101) {
          EasyLoading.showToast("网络异常，请检查网路");
          return;
        }
      } else {
        if (e.response.statusCode == 404) {
          EasyLoading.showToast("服务器连接异常");
          return;
        }
        if (e.response.statusCode == 500) {
          EasyLoading.showToast("服务器异常");
          return;
        }
        if (e.response.statusCode == 401 || e.response.statusCode == 400) {
          EasyLoading.showToast(e.response.data['msg'].toString());
          return;
        }
      }
    }
  }
}
